import { NineSliceSprite,Texture } from "pixi.js";
import { ImageManager } from "@/managers/ImageManager.js";
import { TexturePool } from "@/utils/TexturePool.js";

export class Sprite_FrameBase extends NineSliceSprite{
    static texture=null;
    static sourceName='';
    static oldSourceName='';
    /**
     * 
     * @param {{
     * name,
     * width,
     * height,
     * left,
     * top,
     * right,
     * bottom
     * }} options 
     */
    constructor(options){
        let ctor=new.target;
        if(!ctor.texture){
            ctor.texture=TexturePool.newTexture();
            ctor.texture.dynamic=true;
        }
        super({
            texture:ctor.texture,
            width:options.width,
            height:options.height,
            leftWidth:options.left,
            topHeight:options.top,
            rightWidth:options.right,
            bottomHeight:options.bottom
        }); 
        
        if(options.name&&options.name!=ctor.sourceName){
            ctor.oldSourceName=ctor.sourceName;
            ImageManager.loadSystem(options.name).then(source=>{
                if(this.constructor.oldSourceName){
                    ImageManager.releaseSystem(this.constructor.oldSourceName);
                }
                let texture=this.constructor.texture;
                
                texture.source=source;
                texture.noFrame=true;
                texture.update();
                texture.noFrame=false;
                source.off('resize',texture.update,texture);
            });
            ctor.sourceName=options.name;
        }
        if(!ctor.texture.refCount){
            ctor.texture.refCount=0;
        }
        ++ctor.texture.refCount;
    }

    destroy(opts){
        if(this.destroyed)return;
        opts=opts||{children:true};
        if(opts.texture){
            opts.texture=false;
        }
        if(opts.textureSource){
            opts.textureSource=false;
        }
        let texture=this.constructor.texture;
        --texture.refCount;
        texture.off('update',this.onViewUpdate, this);
        if(texture.refCount<=0){
            texture.refCount=0;
            ImageManager.releaseSystem(this.constructor.sourceName);
            TexturePool.releaseTexture(texture);
            this.clear();
        }
        super.destroy(opts);
    }

    resize(width,height){
        this.setSize(width,height);
    }

    move(x,y){
        this.x=x;
        this.y=y;
    }

    clear(){
        let ctor=this.constructor;
        ctor.texture=null;
        ctor.sourceName='';
    }
}